<?php

use Core\AdminController;
use Models\Brand;
use Models\Category;

class BrandController extends AdminController
{
	public function __construct()
	{
		parent::__construct();
		$this->lang->load('admin_brand', $this->session->admin_language);
	}

	public function index()
	{
		$brand = new Brand;
		if($this->input->get('keyword')){
			$brand->like('title',$this->input->get('keyword'));
			$brand->or_like('en_title',$this->input->get('keyword'));
		}
		$page = $brand->order_by('en_title asc, sort desc ,id desc')
		->paginate(20);

		$this->load->view('admin/brand/index', [
			'page' => $page
		]);
	}

	// 创建品牌
	public function create()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('title', '名称', 'required|max_length[32]')
		->set_rules('en_title', '英文名称', 'required|max_length[32]')
		->set_rules('image', '图片', 'trim')
		->set_rules('sort', '排序', 'integer')
		->set_rules('categories[]', '包含分类', 'integer');
		if ($this->form_validation->run()) {
			$brand = new Brand();
			$brand->load($this->input->post());
			
			if ($this->input->post('categories')) {
				$brand['categories'] = implode(',', $this->input->post('categories'));
			}

			$brand->add();

			return $this->success();
		}

		$categories = Category::where('parent_id', 0)->get();
		
		return $this->load->view('admin/brand/create', [
			'categories' => $categories
		]);
	}

	public function edit($id)
	{
		$brand = new Brand();
		if (!$brand->find($id)) {
			show_404();
		}

		$this->load->library('form_validation');
		$this->form_validation->set_rules('title', '名称', 'required|max_length[32]')
		->set_rules('en_title', '英文名称', 'required|max_length[32]')
		->set_rules('image', '图片', 'trim')
		->set_rules('sort', '排序', 'integer')
		->set_rules('categories[]', '包含分类', 'integer');

		if ($this->form_validation->run()) {
			$brand->load($this->input->post());

			if ($this->input->post('categories')) {
				$brand['categories'] = implode(',', $this->input->post('categories'));
			}

			$brand->update();
			return $this->success();
		}
		$categories = Category::where('parent_id', 0)->get();

		return $this->load->view('admin/brand/edit', [
			'categories' => $categories,
			'brand' => $brand,
		]);
	}

	public function delete($id)
	{
		$brand = new Brand();
		if (!$brand->find($id)) {
			show_404();
		}
		$file = APPPATH.$brand['image'];
		if ($brand['image'] && file_exists($file)) {
			unlink($file);
		}
		$brand->delete();

		return $this->response(['error' => 'success']);
	}
}